/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.ts.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.Msg.domain.Msg;
import com.fzhucc.modules.Msg.domain.dto.SmallMsgDto;
import com.fzhucc.modules.Msg.repository.MsgRepository;
import com.fzhucc.modules.fenRecordLog.service.FenRecordLogService;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfo;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfoLesson;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfoResult;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfoWe;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.*;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemand;
import com.fzhucc.modules.sciTechnologyDemand.domain.dto.AllowSciTechnologyDemandDto;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.domain.UserSmall;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.repository.UserSmallRepository;
import com.fzhucc.modules.system.service.DictDetailService;
import com.fzhucc.modules.system.service.DictService;
import com.fzhucc.modules.system.service.dto.DictDetailDto;
import com.fzhucc.modules.system.service.dto.DictDto;
import com.fzhucc.modules.system.service.dto.DictQueryCriteria;
import com.fzhucc.modules.ts.domain.TsTeam;
import com.fzhucc.modules.ts.domain.TsTeamCons;
import com.fzhucc.modules.ts.domain.dto.*;
import com.fzhucc.modules.ts.repository.TsTeamConsRepository;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.ts.repository.TsTeamRepository;
import com.fzhucc.modules.ts.service.mapstruct.TsTeamMapper;
import org.apache.commons.lang3.function.FailableObjDoubleConsumer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-12-07
 **/
@Service
@RequiredArgsConstructor
public class TsTeamService {

    private final TsTeamRepository tsTeamRepository;

    private final TsTeamConsRepository tsTeamConsRepository;
    private final TsTeamMapper tsTeamMapper;

    private final DictService dictService;

    private final DictDetailService dictDetailService;

    private final UserRepository userRepository;
    private final MsgRepository msgRepository;

    private final UserSmallRepository userSmallRepository;

    private final FenRecordLogService fenRecordLogService;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Value("${sci.audit.qxdsh}")
    public String qxdsh;

    @Value("${sci.audit.sjdsh}")
    public String sjdsh;

    @Value("${sci.audit.shtg}")
    public String shtg;

    @Value("${sci.audit.bh}")
    public String bh;

    @Value("${fen.type.fwd}")
    public String fwd;

    public Map<String, Object> queryAll(TsTeamQueryCriteria criteria, Pageable pageable) {
        //管理端根据登录用户地区
        String str = setCriteria(criteria);
        if (str == null) {
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //表示为省总账号 且输入模糊查询
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
            } else {
                criteria.setOrgArea(str);
            }
        } else {
            //criteria.setOrgArea(str);
            //TODO 添加判断第三级   是否包含在第二级中   则采用第三级的查询
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length == 3) {
                if (str.contains(criteria.getOrgAreas()[1])) {
                    criteria.setOrgArea(criteria.getOrgAreas()[2]);
                }
            } else {
                criteria.setOrgArea(str);
            }
        }
        criteria.setIsDelete(0);
        criteria.setOrgAreas(null);
        Page<TsTeam> page = tsTeamRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<TsTeamDto> map = page.map(tsTeamMapper::toDto);
        List<TsTeamDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (TsTeamDto tsTeamDto : list) {
                Integer id = tsTeamDto.getId();
                List<TsTeamCons> results = tsTeamConsRepository.findByTsId(id);
                tsTeamDto.setListTeams(results);

                String orgArea = tsTeamDto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    tsTeamDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    tsTeamDto.setOrgAreas(array);
                }

                String area = tsTeamDto.getArea();
                if (area != null && area.contains(";")) {
                    String[] array = area.split(";");
                    tsTeamDto.setAreas(array);
                } else {
                    String[] array = {};
                    tsTeamDto.setAreas(array);
                }

                String showPic = tsTeamDto.getShowPic();
                if (showPic != null && showPic.contains(";")) {
                    String[] array = showPic.split(";");
                    tsTeamDto.setShowPics(array);
                } else {
                    String[] array = {};
                    tsTeamDto.setShowPics(array);
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public Map<String, Object> queryAllh5(TsTeamQueryCriteria criteria, Pageable pageable) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(fwd);
        } catch (Exception e) {

        }
        criteria.setIsDelete(0);
        if (criteria.getOrgArea() != null && criteria.getOrgArea().equals(all)) {
            //h5的直接传orgArea
            criteria.setOrgArea(null);
        }
        Page<TsTeam> page = tsTeamRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<TsTeamDto> map = page.map(tsTeamMapper::toDto);
        List<TsTeamDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (TsTeamDto tsTeamDto : list) {
                Integer id = tsTeamDto.getId();
                List<TsTeamCons> results = tsTeamConsRepository.findByTsId(id);
                tsTeamDto.setListTeams(results);

                String orgArea = tsTeamDto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    tsTeamDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    tsTeamDto.setOrgAreas(array);
                }

                String area = tsTeamDto.getArea();
                if (area != null && area.contains(";")) {
                    String[] array = area.split(";");
                    tsTeamDto.setAreas(array);
                } else {
                    String[] array = {};
                    tsTeamDto.setAreas(array);
                }

                String showPic = tsTeamDto.getShowPic();
                if (showPic != null && showPic.contains(";")) {
                    String[] array = showPic.split(";");
                    tsTeamDto.setShowPics(array);
                } else {
                    String[] array = {};
                    tsTeamDto.setShowPics(array);
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public List<TsTeamDto> queryAllmy(TsTeamQueryCriteria criteria) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("未找到登录用户");
        }
        criteria.setUserId(userId);
        criteria.setIsDelete(0);
        return tsTeamMapper.toDto(tsTeamRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public Map<String, Object> my(TsTeamQueryCriteria criteria, Pageable pageable) {
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        criteria.setIsDelete(0);
        Page<TsTeam> page = tsTeamRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<TsTeamDto> map = page.map(tsTeamMapper::toDto);
        List<TsTeamDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (TsTeamDto tsTeamDto : list) {
                Integer id = tsTeamDto.getId();
                List<TsTeamCons> results = tsTeamConsRepository.findByTsId(id);
                tsTeamDto.setListTeams(results);

                String orgArea = tsTeamDto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    tsTeamDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    tsTeamDto.setOrgAreas(array);
                }

                String area = tsTeamDto.getArea();
                if (area != null && area.contains(";")) {
                    String[] array = area.split(";");
                    tsTeamDto.setAreas(array);
                } else {
                    String[] array = {};
                    tsTeamDto.setAreas(array);
                }

                String showPic = tsTeamDto.getShowPic();
                if (showPic != null && showPic.contains(";")) {
                    String[] array = showPic.split(";");
                    tsTeamDto.setShowPics(array);
                } else {
                    String[] array = {};
                    tsTeamDto.setShowPics(array);
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public List<TsTeamDto> queryAll(TsTeamQueryCriteria criteria) {
        //导出  如果有传则按传的数组 导出
        criteria.setIsDelete(0);
        String str = setCriteria(criteria);
        if (str == null) {
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //表示为省总账号 且输入模糊查询
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
            } else {
                criteria.setOrgArea(str);
            }
        } else {
            //criteria.setOrgArea(str);
            //TODO 添加判断第三级   是否包含在第二级中   则采用第三级的查询
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length == 3) {
                if (str.contains(criteria.getOrgAreas()[1])) {
                    criteria.setOrgArea(criteria.getOrgAreas()[2]);
                }
            } else {
                criteria.setOrgArea(str);
            }
        }
        return tsTeamMapper.toDto(tsTeamRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Transactional
    public TsTeamDto findById(Integer id) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(fwd);
        } catch (Exception e) {

        }

        TsTeam tsTeam = tsTeamRepository.findById(id).orElseGet(TsTeam::new);
        ValidationUtil.isNull(tsTeam.getId(), "TsTeam", "id", id);
        //查询热度 +1
        Integer hot = tsTeam.getHot();
        tsTeam.setHot(hot + 1);
        TsTeam save = tsTeamRepository.save(tsTeam);
        TsTeamDto tsTeamDto = tsTeamMapper.toDto(save);

        List<TsTeamCons> results = tsTeamConsRepository.findByTsId(tsTeamDto.getId());
        tsTeamDto.setListTeams(results);
        String orgArea = tsTeamDto.getOrgArea();
        if (orgArea != null && orgArea.contains(";")) {
            String[] array = orgArea.split(";");
            tsTeamDto.setOrgAreas(array);
        } else {
            String[] array = {};
            tsTeamDto.setOrgAreas(array);
        }

        String showPic = tsTeamDto.getShowPic();
        if (showPic != null && showPic.contains(";")) {
            String[] array = showPic.split(";");
            tsTeamDto.setShowPics(array);
        } else {
            String[] array = {};
            tsTeamDto.setShowPics(array);
        }

        String area = tsTeamDto.getArea();
        if (area != null && area.contains(";")) {
            String[] array = area.split(";");
            tsTeamDto.setAreas(array);
        } else {
            String[] array = {};
            tsTeamDto.setAreas(array);
        }

        List<Msg> listMsg = msgRepository.findNormalByGlIdWithAuditStatus(tsTeamDto.getId(), "审核通过","%服务队%");
        if (listMsg != null && listMsg.size() > 0) {
            List<SmallMsgDto> myList = new ArrayList<SmallMsgDto>();
            for (Msg msg : listMsg) {
                SmallMsgDto smallMsgDto = new SmallMsgDto();
                smallMsgDto.setId(msg.getId());
                smallMsgDto.setGlId(msg.getGlId());
                smallMsgDto.setType(msg.getType());
                smallMsgDto.setContext(msg.getContext());
                smallMsgDto.setAuditStatus(msg.getAuditStatus());
                smallMsgDto.setUserId(msg.getUserId());
                smallMsgDto.setUpdateBy(msg.getUpdateBy());
                smallMsgDto.setCreateTime(msg.getCreateTime());
                smallMsgDto.setCreateBy(msg.getCreateBy());
                smallMsgDto.setUpdateTime(msg.getUpdateTime());
                Optional<UserSmall> res = userSmallRepository.findById(msg.getUserId());
                if (res.isPresent()) {
                    smallMsgDto.setUserSmall(res.get());
                }
                myList.add(smallMsgDto);
            }
            tsTeamDto.setMsgDto(myList);
        }
        return tsTeamDto;
    }

    @Transactional(rollbackFor = Exception.class)
    public void isAllowEdit(AllowTsTeamDto dto) {
        Optional<TsTeam> res = tsTeamRepository.findById(dto.getId());
        if (!res.isPresent()) {
            throw new BadRequestException("技术服务队信息表id");
        }
        Integer isEdit = dto.getIsEdit();
        if (isEdit == null) {
            throw new BadRequestException("缺少参数");
        }
        if (isEdit != 0 && isEdit != 1) {
            throw new BadRequestException("参数错误无法操作");
        }
        TsTeam tsTeam = res.get();
        tsTeam.setIsEdit(isEdit);
        tsTeamRepository.save(tsTeam);
    }

    @Transactional(rollbackFor = Exception.class)
    public TsTeamDto create(TsTeamAddDto dto) {
        TsTeam tsTeam = new TsTeam();
        tsTeam.setDetails(dto.getDetails());
        tsTeam.setInfoName(dto.getInfoName());
        tsTeam.setName1(dto.getName1());
        tsTeam.setName2(dto.getName2());
        tsTeam.setEducation1(dto.getEducation1());
        tsTeam.setEducation2(dto.getEducation2());
        tsTeam.setTitle1(dto.getTitle1());
        tsTeam.setIsEdit(0);
        tsTeam.setTitle2(dto.getTitle2());
        tsTeam.setHot(0);
        tsTeam.setSqType(dto.getSqType());
        tsTeam.setUserId(SecurityUtils.getCurrentUserId());
        tsTeam.setType1(dto.getType1());
        tsTeam.setType2(dto.getType2());
        tsTeam.setExpertise1(dto.getExpertise1());
        tsTeam.setExpertise2(dto.getExpertise2());
        tsTeam.setPhone1(dto.getPhone1());
        tsTeam.setPhone2(dto.getPhone2());
        if (dto.getAreas() != null && dto.getAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getAreas()) {
                last = last + a + ";";
            }
            tsTeam.setArea(last);
        } else {
            tsTeam.setArea(null);
        }
        tsTeam.setPic(dto.getPic());
        tsTeam.setSpeciality1(dto.getSpeciality1());
        tsTeam.setSpeciality2(dto.getSpeciality2());
        tsTeam.setMans(dto.getMans());
        tsTeam.setIndustrySector(dto.getIndustrySector());
        tsTeam.setResult(dto.getResult());
        tsTeam.setIsDelete(0);
        tsTeam.setIsShow(0);
        tsTeam.setSort(1);
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            tsTeam.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            tsTeam.setOrgArea(orgAreaReturn());
        }
        if (dto.getShowPics() != null && dto.getShowPics().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getShowPics()) {
                last = last + a + ";";
            }
            tsTeam.setShowPic(last);
        } else {
            tsTeam.setShowPic(null);
        }
        tsTeam.setShowVideo(dto.getShowVideo());
        tsTeam.setAuditStatus(qxdsh);
        TsTeam tsTeam2 = tsTeamRepository.save(tsTeam);

        //根据id设置sort
        Optional<TsTeam> result = tsTeamRepository.findById(tsTeam2.getId());
        if (result.isPresent()) {
            TsTeam sciCxResult = result.get();
            sciCxResult.setSort(sciCxResult.getId());
            tsTeamRepository.save(sciCxResult);
        }

        List<TsTeamConsAddDto> list = dto.getListTeams();
        if (list != null && list.size() > 0) {
            for (TsTeamConsAddDto res : list) {
                TsTeamCons res1 = new TsTeamCons();
                res1.setPhone(res.getPhone());
                res1.setEducation(res.getEducation());
                res1.setName(res.getName());
                res1.setTitle(res.getTitle());
                res1.setSpeciality(res.getSpeciality());
                res1.setExpertise(res.getExpertise());
                res1.setIsModel(res.getIsModel());
                res1.setTsId(tsTeam2.getId());
                tsTeamConsRepository.save(res1);
            }
        }
        TsTeamDto tsTeamDto = tsTeamMapper.toDto(tsTeam2);
        Integer id = tsTeamDto.getId();
        List<TsTeamCons> results = tsTeamConsRepository.findByTsId(id);
        tsTeamDto.setListTeams(results);
        return tsTeamDto;
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(TsTeamEditDto dto) {
        TsTeam tsTeam = tsTeamRepository.findById(dto.getId()).orElseGet(TsTeam::new);
        //TODO 如果编辑时为驳回状态则 调整为区县待审核
        if (tsTeam.getAuditStatus().equals(bh)){
            tsTeam.setAuditStatus(qxdsh);
        }
        ValidationUtil.isNull(tsTeam.getId(), "TsTeam", "id", dto.getId());

        tsTeam.setDetails(dto.getDetails());
        tsTeam.setInfoName(dto.getInfoName());
        tsTeam.setName1(dto.getName1());
        tsTeam.setName2(dto.getName2());
        tsTeam.setEducation1(dto.getEducation1());
        tsTeam.setEducation2(dto.getEducation2());
        tsTeam.setTitle1(dto.getTitle1());
        tsTeam.setTitle2(dto.getTitle2());
        //tsTeam.setUserId(SecurityUtils.getCurrentUserId());
        tsTeam.setType1(dto.getType1());
        tsTeam.setSqType(dto.getSqType());
        tsTeam.setType2(dto.getType2());
        tsTeam.setPic(dto.getPic());
        tsTeam.setExpertise1(dto.getExpertise1());
        tsTeam.setExpertise2(dto.getExpertise2());
        tsTeam.setSpeciality1(dto.getSpeciality1());
        tsTeam.setSpeciality2(dto.getSpeciality2());
        tsTeam.setPhone1(dto.getPhone1());
        tsTeam.setPhone2(dto.getPhone2());
        if (dto.getAreas() != null && dto.getAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getAreas()) {
                last = last + a + ";";
            }
            tsTeam.setArea(last);
        } else {
            tsTeam.setArea(null);
        }
        tsTeam.setMans(dto.getMans());
        tsTeam.setIndustrySector(dto.getIndustrySector());
        tsTeam.setResult(dto.getResult());
        tsTeam.setIsDelete(dto.getIsDelete());
        tsTeam.setIsShow(dto.getIsShow());
        tsTeam.setSort(dto.getSort());
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            tsTeam.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            tsTeam.setOrgArea(orgAreaReturn());
        }
        if (dto.getShowPics() != null && dto.getShowPics().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getShowPics()) {
                last = last + a + ";";
            }
            tsTeam.setShowPic(last);
        } else {
            tsTeam.setShowPic(null);
        }
        tsTeam.setShowVideo(dto.getShowVideo());
        //tsTeam.setAuditStatus(dto.getAuditStatus());
        //tsTeam.setSAuditStatus(dto.getSAuditStatus());
        TsTeam tsTeam2 = tsTeamRepository.save(tsTeam);
        List<TsTeamConsAddDto> list = dto.getListTeams();
        if (list != null && list.size() > 0) {
            List<TsTeamCons> all1 = tsTeamConsRepository.findByTsId(tsTeam2.getId());
            if (all1 != null && all1.size() > 0) {
                for (TsTeamCons result : all1) {
                    tsTeamConsRepository.deleteById(result.getId());
                }
            }
            for (TsTeamConsAddDto res : list) {
                TsTeamCons res1 = new TsTeamCons();
                res1.setPhone(res.getPhone());
                res1.setEducation(res.getEducation());
                res1.setName(res.getName());
                res1.setTitle(res.getTitle());
                res1.setSpeciality(res.getSpeciality());
                res1.setExpertise(res.getExpertise());
                res1.setIsModel(res.getIsModel());
                res1.setTsId(tsTeam2.getId());
                tsTeamConsRepository.save(res1);
            }
        }
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            //tsTeamRepository.deleteById(id);
            //假删除
            Optional<TsTeam> res = tsTeamRepository.findById(id);
            if (res.isPresent()) {
                TsTeam tsTeam = res.get();
                tsTeam.setIsDelete(1);
                Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
                tsTeam.setDeleteTime(currentTimestamp);
                tsTeamRepository.save(tsTeam);
            }
        }
    }

    public void download(List<TsTeamDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TsTeamDto tsTeam : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("技术信息表名称", tsTeam.getInfoName());
            map.put("队长名称", tsTeam.getName1());
            map.put("副队长名称", tsTeam.getName2());
            map.put("队长学历", tsTeam.getEducation1());
            map.put("副队长学历", tsTeam.getEducation2());
            map.put("队长职称", tsTeam.getTitle1());
            map.put("副队长职称", tsTeam.getTitle2());
            map.put("队长劳模工匠人才类型", tsTeam.getType1());
            map.put("副队长劳模工匠人才类型", tsTeam.getType2());
            map.put("队长专长", tsTeam.getExpertise1());
            map.put("副队长专长", tsTeam.getExpertise2());
            map.put("队长专业", tsTeam.getSpeciality1());
            map.put("副队长专业", tsTeam.getSpeciality2());
            map.put("队长联系电话", tsTeam.getPhone1());
            map.put("副队长联系电话", tsTeam.getPhone2());
            map.put("所在区域/系统", tsTeam.getArea());
            map.put("人数", tsTeam.getMans());
            map.put("行业领域", tsTeam.getIndustrySector());
            map.put("服务能力简介", tsTeam.getDetails());
            map.put("图片", tsTeam.getPic());
            map.put("服务成果案例", tsTeam.getResult());
            map.put("是否删除 默认否", tsTeam.getIsDelete());
            map.put("地区组织机构区分", tsTeam.getOrgArea());
            map.put("审核状态", tsTeam.getAuditStatus());
            map.put("是否小程序展示", tsTeam.getIsShow());
            map.put("排序", tsTeam.getSort());
            map.put("填报用户", tsTeam.getUserId());
            map.put("热度", tsTeam.getHot());
            map.put("是否编辑", tsTeam.getIsEdit());
            map.put("展示图片", tsTeam.getShowPic());
            map.put("展示视频", tsTeam.getShowVideo());
            map.put("区县级区分", tsTeam.getSqType());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Transactional(rollbackFor = Exception.class)
    public void audit(TsInfoDto dto) {
        Optional<TsTeam> res = tsTeamRepository.findById(dto.getId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到技术服务队id");
        }
        String cAuditStatus = dto.getAuditStatus();
        if (cAuditStatus == null || cAuditStatus.equals("")) {
            throw new BadRequestException("缺少审核状态");
        }
        TsTeam tsTeam = res.get();
        //TODO 根据登录用户如果是市 的则审核市的字段    如果是区的则审核区的字段  admin暂不处理
        Long userId = SecurityUtils.getCurrentUserId();
        Optional<User> resUser = userRepository.findById(userId);
        if (!resUser.isPresent()) {
            throw new BadRequestException("未找到登录用户");
        }
        User user = resUser.get();
        String orgArea = user.getOrgArea();
        //TODO 如果orgArea里面有2个 ; 表示市级审核   3个; 表示区级审核  其他则不与通过
        if (orgArea == null || orgArea.equals("")) {
            throw new BadRequestException("缺少地区区域无法审核");
        }
        if (!orgArea.contains(";")) {
            throw new BadRequestException("地区区域不符合规范无法审核");
        }
        String[] results = orgArea.split(";");
        if (results.length == 1) {
            throw new BadRequestException("省级账号无法审核");
        } else if (results.length == 2) {
            if (cAuditStatus.equals(bh)) {//驳回
                if (!tsTeam.getAuditStatus().equals(sjdsh)) {
                    throw new BadRequestException("区级审核未通过,无法操作");
                }
                //市级审核驳回 就变成区级待审核
                tsTeam.setAuditStatus(qxdsh);
                tsTeam.setIsEdit(1);//驳回设置为可编辑
                tsTeamRepository.save(tsTeam);
            } else if (cAuditStatus.equals(shtg)) {
                if (!tsTeam.getAuditStatus().equals(sjdsh)) {
                    throw new BadRequestException("区级审核未通过,无法操作");
                }
                //区级审核通过 市级审核通过则通过
                tsTeam.setAuditStatus(shtg);
                //审核通过设为显示
                tsTeam.setIsShow(1);
                if (tsTeam.getIsEdit() == 1) {

                } else {
                    tsTeam.setIsEdit(0); //打开了允许编辑就不管他 否住则设置为不可编辑
                }
                tsTeamRepository.save(tsTeam);
            } else {
                throw new BadRequestException("未符合规范的类型,无法审核");
            }
        } else if (results.length == 3) {
            if (cAuditStatus.equals(bh)) {//驳回
                //区级审核
                tsTeam.setAuditStatus(cAuditStatus);
                tsTeam.setIsEdit(1);//驳回设置为可编辑
                tsTeamRepository.save(tsTeam);
            } else if (cAuditStatus.equals(shtg)) {
                //区级审核通过 变为市级待审核
                tsTeam.setAuditStatus(sjdsh);
                if (tsTeam.getIsEdit() == 1) {

                } else {
                    tsTeam.setIsEdit(0); //打开了允许编辑就不管他 否住则设置为不可编辑
                }
                tsTeamRepository.save(tsTeam);
            } else {
                throw new BadRequestException("未符合规范的类型,无法审核");
            }
        } else {
            throw new BadRequestException("未符合的审级权限无法审核");
        }
    }

    public List<DictDetailDto> getTTA() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("technology_team-area");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    public List<DictDetailDto> getTTM() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("technology_team-main");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    //根据不同设置不同的部门查看
    public String setCriteria(TsTeamQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && (orgArea.equals(all) || orgArea.equals(all2))) { //如果等于福建省则查全部
                return null;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//用的org组织最高看全部
                return null;
            } else {
                return res.getOrgArea();//如果用户的权限不是福建省则 只能看到对应的组织
            }
        } else {
            return null;
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            return res.getOrgArea();
        }
    }

    public Boolean createAll(TsTeamAddDto dto) {
        TsTeam tsTeam = new TsTeam();
        tsTeam.setDetails(dto.getDetails());
        tsTeam.setInfoName(dto.getInfoName());
        tsTeam.setName1(dto.getName1());
        tsTeam.setName2(dto.getName2());
        tsTeam.setEducation1(dto.getEducation1());
        tsTeam.setEducation2(dto.getEducation2());
        tsTeam.setTitle1(dto.getTitle1());
        tsTeam.setTitle2(dto.getTitle2());
        tsTeam.setUserId(SecurityUtils.getCurrentUserId());
        tsTeam.setType1(dto.getType1());
        tsTeam.setType2(dto.getType2());
        tsTeam.setSqType(dto.getSqType());
        tsTeam.setHot(0);
        tsTeam.setIsEdit(0);
        tsTeam.setSpeciality1(dto.getSpeciality1());
        tsTeam.setSpeciality2(dto.getSpeciality2());
        tsTeam.setExpertise1(dto.getExpertise1());
        tsTeam.setExpertise2(dto.getExpertise2());
        tsTeam.setPhone1(dto.getPhone1());
        tsTeam.setPhone2(dto.getPhone2());
        tsTeam.setPic(dto.getPic());
        if (dto.getAreas() != null && dto.getAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getAreas()) {
                last = last + a + ";";
            }
            tsTeam.setArea(last);
        } else {
            tsTeam.setArea(null);
        }
        tsTeam.setMans(dto.getMans());
        tsTeam.setIndustrySector(dto.getIndustrySector());
        tsTeam.setResult(dto.getResult());
        tsTeam.setIsDelete(0);
        tsTeam.setIsShow(0);
        tsTeam.setSort(1);
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            tsTeam.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            tsTeam.setOrgArea(orgAreaReturn());
        }
        if (dto.getShowPics() != null && dto.getShowPics().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getShowPics()) {
                last = last + a + ";";
            }
            tsTeam.setShowPic(last);
        } else {
            tsTeam.setShowPic(null);
        }
        tsTeam.setShowVideo(dto.getShowVideo());
        tsTeam.setAuditStatus(qxdsh);
        TsTeam tsTeam2 = tsTeamRepository.save(tsTeam);

        //根据id设置sort
        Optional<TsTeam> result = tsTeamRepository.findById(tsTeam2.getId());
        if (result.isPresent()) {
            TsTeam sciCxResult = result.get();
            sciCxResult.setSort(sciCxResult.getId());
            tsTeamRepository.save(sciCxResult);
        }
        List<TsTeamConsAddDto> list = dto.getListTeams();
        if (list != null && list.size() > 0) {
            for (TsTeamConsAddDto res : list) {
                TsTeamCons res1 = new TsTeamCons();
                res1.setPhone(res.getPhone());
                res1.setEducation(res.getEducation());
                res1.setName(res.getName());
                res1.setTitle(res.getTitle());
                res1.setSpeciality(res.getSpeciality());
                res1.setExpertise(res.getExpertise());
                res1.setIsModel(res.getIsModel());
                res1.setTsId(tsTeam2.getId());
                tsTeamConsRepository.save(res1);
            }
        }

        if (tsTeam2 != null) {
            return true;
        } else {
            return false;
        }
    }


    public TsCityCountryInfoDto cityCountyLevelList(TsTeamCityCountyQueryCriteria criteria) {
        TsCityCountryInfoDto tsCityCountryInfoDto = new TsCityCountryInfoDto();

        String one = criteria.getOrgArea();
        String a = one + "总工会（本级）";
        String last = "%" + a + "%";

        /*String b = "福建省;" + one;
        String last2 = "%" + b + "%";*/
        String c = "福建省;" + one + ";";
        //String last3 = "%" + c + "%";

        String d = "福建省;" + one + ";" + one + "总工会（本级）;";

        List<TsTeam> listNormal = tsTeamRepository.findNormalByLikeAreaWithIsShow(last, shtg, c);
        List<TsTeamDto> tsTeamDtos = tsTeamMapper.toDto(listNormal);
        if (tsTeamDtos != null && tsTeamDtos.size() > 0) {
            for (TsTeamDto tsTeamDto : tsTeamDtos) {
                Integer id = tsTeamDto.getId();
                List<TsTeamCons> results = tsTeamConsRepository.findByTsId(id);
                tsTeamDto.setListTeams(results);

                String orgArea = tsTeamDto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    tsTeamDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    tsTeamDto.setOrgAreas(array);
                }
            }
        }
        tsCityCountryInfoDto.setCityList(tsTeamDtos);


        List<TsTeam> listNormal2 = tsTeamRepository.findNormalByLikeAreaWithIsShow2("%" + one + "%", shtg, d, c);
        List<TsTeamDto> tsTeamDtos2 = tsTeamMapper.toDto(listNormal2);
        if (tsTeamDtos2 != null && tsTeamDtos2.size() > 0) {
            for (TsTeamDto tsTeamDto : tsTeamDtos2) {
                Integer id = tsTeamDto.getId();
                List<TsTeamCons> results = tsTeamConsRepository.findByTsId(id);
                tsTeamDto.setListTeams(results);

                String orgArea = tsTeamDto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    tsTeamDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    tsTeamDto.setOrgAreas(array);
                }
            }
        }
        tsCityCountryInfoDto.setCountryList(tsTeamDtos2);


        return tsCityCountryInfoDto;
    }

    public TsCityCountryInfoDto cityCountyLevelList2(TsTeamCityCountyQueryCriteria criteria) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(fwd);
        } catch (Exception e) {

        }
        TsCityCountryInfoDto tsCityCountryInfoDto = new TsCityCountryInfoDto();
        //orgArea like  然后且为市级的
        String one = criteria.getOrgArea();
        String last = "%" + one + "%";
        List<TsTeam> listNormal = tsTeamRepository.findNormalByLikeAreaWithLikeSqType(shtg, last ,"%市级%");
        List<TsTeamDto> tsTeamDtos = tsTeamMapper.toDto(listNormal);
        if (tsTeamDtos != null && tsTeamDtos.size() > 0) {
            for (TsTeamDto tsTeamDto : tsTeamDtos) {
                Integer id = tsTeamDto.getId();
                List<TsTeamCons> results = tsTeamConsRepository.findByTsId(id);
                tsTeamDto.setListTeams(results);

                String orgArea = tsTeamDto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    tsTeamDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    tsTeamDto.setOrgAreas(array);
                }
            }
        }
        tsCityCountryInfoDto.setCityList(tsTeamDtos);


        List<TsTeam> listNormal2 = tsTeamRepository.findNormalByLikeAreaWithLikeSqType(shtg,last, "%区县级%");
        List<TsTeamDto> tsTeamDtos2 = tsTeamMapper.toDto(listNormal2);
        if (tsTeamDtos2 != null && tsTeamDtos2.size() > 0) {
            for (TsTeamDto tsTeamDto : tsTeamDtos2) {
                Integer id = tsTeamDto.getId();
                List<TsTeamCons> results = tsTeamConsRepository.findByTsId(id);
                tsTeamDto.setListTeams(results);

                String orgArea = tsTeamDto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    tsTeamDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    tsTeamDto.setOrgAreas(array);
                }
            }
        }
        tsCityCountryInfoDto.setCountryList(tsTeamDtos2);


        return tsCityCountryInfoDto;
    }
}